
// WebContentActivity.java
package com.example.myaku;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class WebContentFragment extends Fragment {

    private WebView webView;
    private String akuUrl;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            akuUrl = getArguments().getString("AKUurl");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        WebView webView = new WebView(requireContext());

        if (akuUrl != null && !akuUrl.isEmpty()) {
            // 启用 JavaScript（可选）
            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            // 设置 WebViewClient 防止外部浏览器打开
            webView.setWebViewClient(new WebViewClient());
            webView.loadUrl(akuUrl);
        } else {
            webView.loadData("<html><body>没有可用内容</body></html>", "text/html", "UTF-8");
        }

        requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(),
                new OnBackPressedCallback(true) {
                    @Override
                    public void handleOnBackPressed() {
                        if (webView.canGoBack()) {
                            webView.goBack();
                            Log.d("WebContentActivity", "返回网址");
                        } else {
                            setEnabled(false); // 停止拦截，交给系统处理
                            requireActivity().onBackPressed();
                        }
                    }
                }
        );

        return webView;
    }
}